import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_bootstrap_components as dbc

from dash.dependencies import Input, Output, State
from ..api_client import APIClient
from ..app import app


content = dbc.Container([
    html.H2('登录'),
    dcc.Location(id='login-location', refresh=True),
    dbc.Container([
        html.Div([
            dbc.Container(id='login-form', children=[
                dcc.Input(
                    placeholder='邮箱',
                    type='email',
                    id='login-email-input',
                    className='form-control',
                ),
                html.Br(),
                dcc.Input(
                    placeholder='密码',
                    type='password',
                    id='login-password-input',
                    className='form-control',
                ),
                html.Br(),
                html.Button(
                    children='登录',
                    type='submit',
                    id='login-btn',
                    className='btn btn-primary btn-lg'
                ),
                html.Br(),
            ], className='form-group'),
        ]),
    ], className='jumbotron')
])


@app.callback(
    Output('login-location', 'pathname'),
    Input('login-btn', 'n_clicks'),
    State('login-email-input', 'value'),
    State('login-password-input', 'value'),
)
def on_submit_login_form(n_clicks, email, password, *args):
    if not n_clicks:
        raise dash.exceptions.PreventUpdate('stop')

    client = APIClient()
    response = client.login(email, password)

    if response.status_code == 200:
        payload = response.json()
        dash.callback_context.response.set_cookie(
            'access_token', payload['tokens']['access'])

        return '/home'

    # TODO: display error
    return '/login'
